#include "common.hpp"
#include "xbroadcaster.hpp"

XBroadcaster::cont_t XBroadcaster::s_cont;

XBroadcaster::XBroadcaster()
{
	s_cont.insert((intptr_t)this);
}

XBroadcaster::~XBroadcaster()
{
	s_cont.erase((intptr_t)this);
}

size_t
XBroadcaster::broadcast(const char* buf, size_t blen) const
{
	size_t cnt(0);
	cont_citr ib(s_cont.begin());
	cont_citr ie(s_cont.end());
	XBroadcaster* psock;

	while ( ib != ie )
	{
		psock = (XBroadcaster*)(*ib);
		if ( psock != this )
		{
			psock->send(buf, blen, 0);
			++cnt;
		}

		++ib;
	}

	return cnt;
}

bool
XBroadcaster::onReceive(void)
{
	char buf[1024*8];
	size_t rsize( rsize = receive(buf, sizeof(buf), 0) );
	if ( (size_t)-1 == rsize || 0 == rsize )
	{
		return false;
	}

	broadcast(buf, rsize);

	return true;
}

void
XBroadcaster::onEvent(PWIOPoll* io, int fd, int events)
{
	do
	{
		if ( events&PWIO_R )
		{
			if ( !onReceive() )
			{
				break;
			}
		}

		return;
	} while (false);

	gFactory.addRemovedList(this);
	io->remove(this);
}

